using AdminApiTemplate.Cache;
using AdminApiTemplate.Common.Helpers;
using System.Text;

namespace AdminApiTemplate.Api.Helpers
{
    /// <summary>
    /// Api日志操作相关
    /// </summary>
    public class ApiLogHelper
    {
        /// <summary>
        /// 写入Api日志到数据库
        /// </summary>
        /// <param name="apiLog"></param>
        public static void WriteToDb(AddApiLogRequest apiLog)
        {
            var requestHash = SecurityHelper.GetMD5String(apiLog.Request);
            var responseHash = SecurityHelper.GetMD5String(apiLog.Response);
            var errorHash = SecurityHelper.GetMD5String(apiLog.Error);
            var dict = new Dictionary<string, object>
            {
                { "RequestId", apiLog.RequestId },
                { "HttpMethod", apiLog.HttpMethod },
                { "Url", apiLog.Url },
                { "CostTime", apiLog.CostTime },
                { "Success", apiLog.Success },
                { "QueryString", "" },
                { "Request", "" },
                { "RequestHash", requestHash  },
                { "Response", "" },
                { "ResponseHash", responseHash },
                { "Error", "" },
                { "ErrorHash", errorHash },
                { "UserAgent", apiLog.UserAgent },
                { "IP", apiLog.IP },
                { "UserType", apiLog.UserType.ToString() },
                { "UserId", apiLog.UserId },
            };
            if (!string.IsNullOrEmpty(apiLog.QueryString))
            {
                if (apiLog.QueryString.Length>500)
                {
                    apiLog.QueryString = apiLog.QueryString.Substring(0, 500);
                }
                dict["QueryString"] = apiLog.QueryString;
            }

            if (!string.IsNullOrEmpty(apiLog.Request))
            {
                if (apiLog.Request.Length>500)
                {
                    apiLog.Request = apiLog.Request.Substring(0, 500);
                }
                dict["Request"] = apiLog.Request;
            }

            if (!string.IsNullOrEmpty(apiLog.Response))
            {
                if (apiLog.Response.Length>500)
                {
                    apiLog.Response = apiLog.Response.Substring(0, 500);
                }
                dict["Response"] = apiLog.Response;
            }

            if (!string.IsNullOrEmpty(apiLog.Error))
            {
                if (apiLog.Error.Length>500)
                {
                    apiLog.Error = apiLog.Error.Substring(0, 500);
                }
                dict["Error"] = apiLog.Error;
            }

            var sql = @"
INSERT INTO ApiLog
(CreateTime,RequestId,HttpMethod,Url,CostTime,Success,QueryString,Request,RequestHash,Response,ResponseHash,Error,ErrorHash,UserAgent,IP,UserType,UserId) 
VALUES
(NOW(),@RequestId,@HttpMethod,@Url,@CostTime,@Success,@QueryString,@Request,@RequestHash,@Response,@ResponseHash,@Error,@ErrorHash,@UserAgent,@IP,@UserType,@UserId);";
            CacheHelper.DefaultQuery.Execute(sql, dict);
        }

        /// <summary>
        /// 写入Api日志到文件
        /// </summary>
        /// <param name="apiLog"></param>
        public static void WriteToFile(AddApiLogRequest apiLog)
        {
            var sb = new StringBuilder();
            sb.AppendLine($"{apiLog.HttpMethod} {apiLog.Url}");
            sb.AppendLine($"CostTime:{apiLog.CostTime}ms");
            sb.AppendLine($"RequestId:{apiLog.RequestId}");

            if (!string.IsNullOrEmpty(apiLog.QueryString) && apiLog.QueryString.Length<500)
            {
                sb.AppendLine($"QueryString:{apiLog.QueryString}");
            }

            if (!string.IsNullOrEmpty(apiLog.Request) && apiLog.Request.Length<500)
            {
                sb.AppendLine($"Request:{apiLog.Request}");
            }

            if (!string.IsNullOrEmpty(apiLog.Response) && apiLog.Response.Length<500)
            {
                sb.AppendLine($"Response:{apiLog.Response}");
            }

            if (!string.IsNullOrEmpty(apiLog.Error))
            {
                sb.AppendLine($"Error:{apiLog.Error}");
                LogHelper.WriteErrorAsync(sb.ToString());
            }

            LogHelper.WriteAsync(sb.ToString(), "Api");
        }
    }
}
